package com.slashvision.im.chat

import android.os.UserManager
import com.slashvision.im.ContextUtil
import com.slashvision.im.SLog
import com.slashvision.im.TAG
import io.openim.android.sdk.OpenIMClient
import io.openim.android.sdk.listener.OnBase
import io.openim.android.sdk.models.ConversationInfo
import io.openim.android.sdk.models.Message
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.InputStreamReader

/**
 * author : lizhenxin
 *  date  : 2021/11/22
 *  desc  :
 */
/**
 * @desc:
 * @author: LiZhenxin
 * @create:
 * update
 **/

const val TAG_IM = "_TAG_IM_"
class ChatRepository {

    private val mConvManager = OpenIMClient.getInstance().conversationManager



    fun getRecentMsgAsync(
        onResult: (List<ConversationInfo>) -> Unit,
        onErrorr: (code: Long, msg: String) -> Unit
    ) {
        OpenIMClient
            .getInstance()
            .conversationManager
            .getAllConversationList(object : OnBase<List<ConversationInfo>> {
                override fun onError(code: Long, error: String?) {
                    SLog.e(this.TAG(), "获取最近会话出错： ${code}   ${error}")
                    onErrorr(code, error.toString())
                }

                override fun onSuccess(data: List<ConversationInfo>?) {
                    data?.let {
                        SLog.e(this.TAG(), "最近会话${data.size}个")
                        onResult(it)
                    }
                }
            })
    }



    fun getMsgList(friendId: String, onResult: (List<Message>) -> Unit) {
        OpenIMClient.getInstance().messageManager.getHistoryMessageList(
            object : OnBase<List<Message>> {
                override fun onError(code: Long, error: String?) {
                    SLog.e(TAG_IM, "获取消息记录错误：${code}, ${error.toString()}")
                }

                override fun onSuccess(data: List<Message>?) {
                    data?.let {
                        SLog.d(TAG_IM, "获取和${friendId}消息记录共${it.size}条")
                        onResult(it)
                    }
                }
            },
            friendId, null, null, Int.MAX_VALUE
        )
    }



    fun setConvRead(friendId: String) {
        mConvManager.markSingleMessageHasRead(
            object : OnBase<String> {
                override fun onError(code: Long, error: String?) {
                }

                override fun onSuccess(data: String?) {
                }
            },
            friendId
        )
    }

    fun setMsgRead(userId:String, msgIds: List<String>) {
        OpenIMClient.getInstance().messageManager.markC2CMessageAsRead(object : OnBase<String?> {
            override fun onError(code: Long, error: String) {}
            override fun onSuccess(data: String?) {

            }
        }, userId, msgIds)
    }
}